package com.suredy.app.project.service;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.suredy.app.project.model.Project;
import com.suredy.app.project.model.ProjectMember;
import com.suredy.core.service.BaseSrvWithEntity;
import com.suredy.security.entity.UserEntity;

@Service
public class ProjectMemberSrv extends BaseSrvWithEntity<ProjectMember> {

	public ProjectMemberSrv() {
		this.addAnDefOrder("manager", false);
	}

	@Override
	public DetachedCriteria getDc(ProjectMember t) {
		DetachedCriteria dc = super.getDc(t);

		if (t == null)
			return dc;

		if (!StringUtils.isBlank(t.getId())) {
			dc.add(Restrictions.eq("id", t.getId()));
		}
		if (t.getUser() != null) {
			dc.add(Restrictions.eq("user", t.getUser()));
		}
		if (t.getManager() != null) {
			dc.add(Restrictions.eq("user", t.getManager()));
		}
		if (t.getProject() != null) {
			dc.add(Restrictions.eq("project", t.getProject()));
		}

		return dc;
	}

	@Transactional
	public boolean deleteWithIds(Object[] ids) {
		if (ids == null || ids.length <= 0)
			return false;

		String tmp = "";
		for (int i = 0; i < ids.length; i++) {
			if (!StringUtils.isBlank(tmp))
				tmp += ",";

			tmp += "?";
		}

		String ql = "DELETE FROM ProjectMember WHERE id in (" + tmp + ")";

		return this.deleteByQL(ql, ids) >= 0;
	}

	@Transactional
	public boolean updateProjectMembersWithoutManager(String projId, String[] userIds) {
		if (StringUtils.isBlank(projId))
			return false;

		String delete = "DELETE FROM ProjectMember T WHERE T.project.id=? and T.manager=?";

		this.deleteByQL(delete, projId, false);

		if (userIds == null || userIds.length <= 0)
			return true;

		for (String userId : userIds) {
			ProjectMember m = new ProjectMember();

			m.setManager(false);
			m.setProject(new Project());
			m.getProject().setId(projId);
			m.setUser(new UserEntity());
			m.getUser().setId(userId);

			this.save(m);
		}

		return true;
	}
}
